package com.itcast.springboot.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@CrossOrigin
public class LoginController {
    @RequestMapping("/admin/add")
    public String add() {
        return "admin/add";
    }

    @RequestMapping("/admin/update")
    public String update() {
        return "admin/update";
    }

    @RequestMapping("/toLogin")
    public String ToLogin() {
        return "login";
    }

    @PostMapping("/login")
    public String login(String account, String password, Model model) {
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(account, password);
        try {
            subject.login(token);   //执行登录方法，如果没有异常就说明ok了
//            SecurityUtils.getSubject().getSession().setTimeout(10000);
            return "index";
        } catch (UnknownAccountException e) {     //用户名不存在
            model.addAttribute("msg", "用户名错误");
            return "login";
        } catch (IncorrectCredentialsException e) {       //密码不存在
            model.addAttribute("msg", "密码错误");
            return "login";
        }
    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized() {
        return "未经授权无法访问此页面";
    }
}
